<template>
  <div style="position: relative;">
    <el-row>
      <el-col :span="4">
        <el-select v-model="value" clearable @change="handleSelectChange(value)">
          <el-option v-for="(item,index) in shops" :key="index" :label="item.label" :value="item.value"></el-option>
        </el-select>
        <div class="market" v-for="(item,index) in superMarket" :key="index" v-show="market">
          <div>{{item.name}}</div>
        </div>
      </el-col>
      <el-col :span="18">
        <el-button class="begin" @click="handleBegin" :disabled="drawDisabled">开始绘制</el-button>
        <el-button class="cancel" @click="handleCancel">清除绘制</el-button>
        <el-button class="end" @click="handleSure" :disabled="saveDisable">保存绘制</el-button>
        <div id="container" :style="{height:Height}">
          <div v-show="showMapTooltip"
            class="map-tooltip"
            ref="mapTooltip">
            {{ mapTooltipText }}
          </div>
        </div>
      </el-col>
    </el-row>
    <el-dialog 
    :visible.sync="editColorDialog"
    title="修改样式"
    custom-class="edit-color-dialog">
      <el-radio-group v-model="redioValue">
        <el-radio-button label="fill">区域填充</el-radio-button>
        <el-radio-button label="stroke">区域轮廓</el-radio-button>
      </el-radio-group>
      <el-form 
      :model="editColorForm" 
      label-width="100px" 
      label-position="left"
      ref="editColorForm">
        <div class="item"
        v-show="redioValue === 'fill'">
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item 
              label="自定义颜色:" 
              label-position="left">
                <el-input class="input_element" v-model="editColorForm.fill_color"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-color-picker v-model="editColorForm.fill_color">
              </el-color-picker>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item 
              label="透明度:"
              label-position="left">
                <div class="set-opacity">
                  <el-input-number v-model="editColorForm.fill_opacity"
                    class="input_element"
                    controls-position="right"
                    :min="0"
                    :max="100">
                  </el-input-number>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label=" &nbsp; ">
                <!-- <el-input-number v-model="editColorForm.line_weight"
                  class="input_element"
                  controls-position="right"
                  :min="1"
                  :max="5">
                </el-input-number> -->
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="item"
        v-show="redioValue === 'stroke'">
        <el-row :gutter="10">
          <el-col :span="8">
              <el-form-item label="自定义颜色:">
                <el-input v-model="editColorForm.line_color"
                  placeholder=""
                  class="input_element">
                </el-input>
              </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-color-picker v-model="editColorForm.line_color"
              style="vertical-align: middle">
            </el-color-picker>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="透明度:">
              <div class="set-opacity">
                <el-input-number v-model="editColorForm.line_opacity"
                  class="input_element"
                  controls-position="right"
                  :min="0"
                  :max="100">
                </el-input-number>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="轮廓宽度:">
              <el-input-number v-model="editColorForm.line_weight"
                class="input_element"
                controls-position="right"
                :min="1"
                :max="10">
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        </div>
      </el-form>
      <div class="colors">
        <span class="color-item"
          v-for="(item, index) in colors"
          :key="index"
          :style="{'background-color': item}"
          @click="handleColorClick(item)">
        </span>
        <div class="preview">
          <div class="view"
            :style="previewStyle">
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editColorDialog = false">取 消</el-button>
        <el-button type="primary" @click="confirmColor('editColorForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import AMap from 'AMap'
  import * as API_AMap from '@/api/map.js'

  export default {
    data() {
      return {
        value: '',
        market: false,
        GDMap: null,
        mouseTool: '',
        marker: '',
        infoWindow: '',
        polygon: '',
        polyEditor: '',
        drawArrayPath: undefined,
        shops: [
          {
            label: '舟山',
            value: '0'
          }
        ],
        superMarket: [
          {
            id: '0',
            name: '张三的店'
          },
          {
            id: '1',
            name: '李四的店'
          }
        ],
        // 结束禁用
        drawDisabled: false,
        // 保存禁用
        saveDisable: true,
        params: {
          // 店铺的ID
          shop_id: 0, 
          // 多边形的ID,
          polygon_id: undefined, 
          // 覆盖物坐标
          polygon_coords: [], 
          // 外边框线颜色
          line_color: '#FF33FF', 
          // 外边框线的透明度
          line_opacity: '0.2', 
          // 外边框线的宽度
          line_weight: '4', 
          // 多边行填充色
          fill_color: '#1791fc', 
          // 多边形填充透明度
          fill_opacity: '0.4', 
          // 多边形绘制人
          create_name: '张三' 
        },
        // 编辑弹框
        editColorDialog: false,
        // 弹框默认显示的radio
        redioValue: 'fill',
        editColorForm: {
          // 外边框线颜色
          line_color: '#FF33FF', 
          // 外边框线的透明度
          line_opacity: '50', 
          // 外边框线的宽度
          line_weight: '4', 
          // 多边行填充色
          fill_color: '#1791fc', 
          // 多边形填充透明度
          fill_opacity: '70'
        },
        colors: [
          '#D0021B', 
          '#F421AB', 
          '#F57470', 
          '#F7C01C', 
          '#F8E71C', 
          '#FBF585', 
          '#7ED321', 
          '#50E3C2', 
          '#0BB78B', 
          '#0BB78C', 
          '#13F8FF', 
          '#0078FF', 
          '#9013FE', 
          '#B045DF', 
          '#E594F3'],
        drawPointCount: 0,
        showMapTooltip: false,
        mapTooltipText: '单击进行绘制',
        mouseX: 0,
        mouseY: 0
      }
    },
    computed: {
      Height (){
        return document.documentElement.clientHeight - 134 + 'px';
      },
      color () {
        return this.value === 'fill' ? this.editColorForm.fillColor : this.editColorForm.line_color
      },
      previewStyle () {
        return {
          'border-style': 'solid',
          'border-color': this.showToRgba(this.editColorForm.line_color, this.editColorForm.line_opacity / 100),
          'border-width': this.editColorForm.line_weight + 'px',
          'background-color': this.showToRgba(this.editColorForm.fill_color, this.editColorForm.fill_opacity / 100)
        }
      }      
    },
    watch: {
      drawPointCount (value) {
        if (value >= 3) {
          this.mapTooltipText = '双击完成绘制'
        } else {
          this.mapTooltipText = '单击进行绘制'
        }
      }
    },
    created() {

    },
    mounted() {
      this.initMap();
    },
    methods: {
      initMap() {
        this.GDMap = new AMap.Map("container", {
          resizeEnable: true,
          center: [116.473188, 39.993253],
          zoom: 13
        });
        let demoArray = [{
          id: '0',
          name: '张三的点',
          address: '河南省郑州市',
          path: [
            [116.403322, 39.920255],
            [116.410703, 39.897555],
            [116.402292, 39.892353],
            [116.389846, 39.891365]
          ],
          detailed: [116.40000, 39.899999],
          strokeColor: '#4B0082',
          strokeOpacity: 0.5,
          strokeWeight: 3,
          fillColor: "#EE82EE", 
          fillOpacity: 0.4 
        },
        {
          id: '1',
          name: '李四的店',
          address: '河南省巩义市',
          path: [
            [116.410703, 39.920720],
            [116.369648, 39.902945],
            [116.38162, 39.914532]
          ],
          detailed: [116.39, 39.91340],
          strokeColor: "#FF33FF", 
          strokeOpacity: 0.2, 
          strokeWeight: 3, 
          fillColor: "#1791fc", 
          fillOpacity: 0.35
        }];
        demoArray.forEach((item) => {
          this.polygon = new AMap.Polygon({
            map: this.GDMap,
            path: item.path, //设置多边形边界路径
            strokeColor: item.strokeColor, //线颜色
            strokeOpacity: item.strokeOpacity, //线透明度
            strokeWeight: item.strokeWeight, //线宽
            fillColor: item.fillColor, //填充色
            fillOpacity: item.fillOpacity //填充透明度
          });

          this.polygon.on('mouseover', (event) => {
            var info = [];
            info.push("<div><div><img style=\"float:left;\" src=\" https://webapi.amap.com/images/autonavi.png \"/></div> ");
            info.push("<div>" + '店名:' + item.name + "</div>");
            info.push("<div>" + '地址:' + item.address + "</div>");
            info.push("<div>" + 
            '<button  value=" ' + item.id +' " style=\"margin-right:10px;background-color:#6495ED;color:#FFF;padding:6px;border-radius: 6px;border:none\" >' + '编辑节点' + "</button>" + 
            '<button  value=" ' + item.id +' " style=\"margin-right:10px;background-color:#6495ED;color:#FFF;padding:6px;border-radius: 6px;border:none\" >' + '编辑属性' + "</button>" +
              "</div>")
            info.push("<div>" + 
            '<button id="editOption"  value=" ' + item.id +' " style=\"margin-right:10px;background-color:#6495ED;color:#FFF;padding:6px;border-radius: 6px;border:none\" >' + '编辑样式' + "</button>" + 
            '<button id="deleteOption" value=" ' + item.id +' " style=\"margin-right:10px;background-color:#FF34aa;color:#FFF;padding:6px;border-radius: 6px;border:none\" >' + '删除节点' + "</button>" +
              "</div>")
            this.infoWindow = new AMap.InfoWindow({
              content: info.join("<br/>") //使用默认信息窗体框样式，显示信息内容
            });

            this.infoWindow.open(this.GDMap, item.detailed);
            let editOptions = document.getElementById('editOption');
            editOptions.addEventListener('click', (e) => {
              this.editColorDialog = true;
            })

            let deleteOptions = document.getElementById('deleteOption');
            deleteOptions.addEventListener('click', (event) => {
              console.log(244444444444)
              this.$confirm('确认要删除此节点吗?')
                .then((response) => {
                  this.$message({
                    type: 'success',
                    message: '删除成功!'
                  })
                })
                .catch((error) => {
                  this.$message({
                    type: 'warning',
                    message: error
                  })
                });
            })
          })
        }) 
        this.mouseTool = new AMap.MouseTool(this.GDMap);
        this.GDMap.setFitView();
        // 通过事件委托给操作按钮添加点击事件
        // document.getElementsByTagName("button")[0].addEventListener('click', (e) => {
        //   console.log(233)
        //   if (!e.target.value) {
        //     console.log("你点的空白区域")
        //   } else {
        //     let ids = Number(e.target.value)
        //     this.polyEditor = new AMap.PolyEditor(this.GDMap, this.GDMap.getAllOverlays('polygon')[ids]);
        //     this.polyEditor.open();
        //     e.target.innerHTML = '结束编辑';
        //     this.showInfoOut();
        //   }
        // })
      },
      handleBegin() {
        this.drawDisabled = true;
        this.saveDisable = false;
        //使用CSS默认样式定义地图上的鼠标样式
        this.GDMap.setDefaultCursor("crosshair");
        // 监听鼠标进入地图
        this.GDMap.on('mousemove', (event) => {
          this.showMapTooltip = true;
          // this.$refs.mapTooltip.style.background = '#FFF'
          // this.$refs.mapTooltip.style.transform = 'translate(' + e.originEvent.clientX + 'px, ' + e.originEvent.clientY + 'px)';
          this.$refs.mapTooltip.style.left = (event.pixel.x + 60) + 'px'
          this.$refs.mapTooltip.style.top =  (event.pixel.y) + 'px'
        })
        this.mouseTool.polygon({
          fillColor: '#00b0ff',
          strokeColor: '#80d8ff'
        });
        this.GDMap.on('click', (event) => {
          this.drawPointCount ++
        })
        this.mouseTool.on('draw', (event) => {
          console.log(event.obj.w.path)
          this.$message({
            type: 'success',
            message: '绘制完成'
          })
          this.mouseTool.close();
          if (event.obj.w.path.length < 3) {
            this.$message({
              type: 'error',
              message: '节点范围最少为3个点,请重新绘制'
            })
            return
          } else {
            this.drawArrayPath = event.obj.w.path
          }
          // console.log(this.drawArrayPath)
        })
      },
      handleSure() {
        if (this.drawArrayPath === undefined) {
          this.$message({
            type: 'error',
            message: '节点范围最少为3个点'
          })
          return
        }
        // API_AMap.addSuperStratum(this.params).then((response) => {
        //   this.$message({
        //     type: 'success',
        //     message: '保存成功, 保存的路径为' + this.drawArrayPath
        //   })
        // })
      },
      handleCancel() {
        console.log(this.polygon.w.path[2])
        this.GDMap.remove(this.polygon.w.path[2])
        // this.drawArrayPath = undefined
      },
      showInfoOut() {
        this.infoWindow.close(this.GDMap)
      },
      handleAdd() {
        console.log(233)
      },
      handleSelectChange(value) {
        if (value === '0') {
          this.market = true
        }
      },
      isActive(color) {
        console.log(color)
        if (this.redioValue === 'fill') {
          console.log(2333)
          // this.editColorForm.fill_color = color
        } else {
          console.log(2444)
          // this.editColorForm.line_color = color
        }
      },
      handleColorClick(color) {
        console.log(color)
        let style = this.editColorForm;
        let value = this.redioValue;
        value === 'fill' ? style.fill_color = color : style.line_color = color;
      },
      showToRgba(hex, trans = 1) {
        let hexColor = /^#/.test(hex) ? hex.slice(1) : hex
        let r
        let g
        let b
        hexColor = /^[0-9a-f]{3}|[0-9a-f]{6}$/i.test(hexColor) ? hexColor : 'fffff'
        if (hexColor.length === 3) {
          hexColor = hexColor.replace(/(\w)(\w)(\w)/gi, '$1$1$2$2$3$3')
        }
        r = hexColor.slice(0, 2)
        g = hexColor.slice(2, 4)
        b = hexColor.slice(4, 6)
        r = parseInt(r, 16)
        g = parseInt(g, 16)
        b = parseInt(b, 16)
        return `rgba(${r}, ${g}, ${b}, ${trans})`
      },
      confirmColor(editColorForm) {
        this.$refs[editColorForm].validate((valide) => {
          if (valide) {
            console.log(this.editColorForm)
            this.$message({
              type: 'success',
              message: '修改样式成功!'
            })
            this.editColorDialog = false;
          }
        })
      }
    }
  }

</script>

<style lang="scss" scoped>
  .market {
    padding: 10px;
    text-align: left;
    color: #22dd22;
    cursor: pointer;

      &:hover {
        background-color: #FF34aa;
      }
  }

  .map-tooltip {
    position: absolute;
    padding: 0 8px;
    margin-left: 12px;
    min-width: 80px;
    line-height: 24px;
    word-wrap: break-word;
    border-radius: 4px;
    text-align: center;
    background: rgba(48, 49, 51, 0.8);
    color: #ffffff;
    font-size: 12px;
    transform: translate(-50%,-50%);
    z-index: 2000;
    &::after {
      content: "";
      position: absolute;
      left: -10px;
      top: 50%;   
      width: 0;
      height: 0;
      font-size: 0;
      border-width: 5px;
      border-color: transparent rgba(48, 49, 51, 0.8) transparent transparent;
      border-style: dashed solid dashed dashed;
      overflow: hidden;
      transform: translateY(-50%);   
    }
  }
  .edit-color-dialog {
    position: relative;

    .item {
      margin-top: 20px;

      .input_element {
        width: 120px;
      }

      .set-opacity {
          position: relative;
          width: 120px;
          &:after {
            content: "%";
            position: absolute;
            right: 54px;
            font-size: 12px;
          }
        }
    }

    .colors {
      display: flex;
      align-items: center;

        .color-item {
          margin-right: 5px;
          width: 30px;
          height: 30px;
          cursor: pointer;
          box-sizing: border-box;

          &.active {
            border: 1px solid #0088cc;
          }
        }
      }

      .preview {
        display: flex;
        align-items: center;
        justify-content: center;   
        position: absolute;
        top: 100px;
        right: 50px;     
        width: 120px;
        height: 120px;
        border: 2px solid #c9d3e0;
        box-sizing: border-box;
        background-color: #fff;
        background-color: #fff;
        .view {
          width: 100px;
          height: 100px;
        }
      }
}

</style>
